'use strict'
var _util = require('../../util/util.js')

var user = JSON.parse(localStorage.getItem('userInfo'))
var userId = user.id;




function getCurrentOrderList(responseData) {
    if (Array.isArray(responseData)) {
        return responseData.map(item => item.order_id);  // 取 order_id 属性
    } else if (typeof responseData === 'object' && responseData !== null) {
        return [responseData.order_id];  // 单个对象也转为数组
    } else {
        return []; // 不合法返回空数组
    }
}

$(function () {

     
    console.log("hello");
    //这里的selectedAddress是id

    // if () {
    //     alert('请先选择或添加一个收货地址');
    // }
    // let addressMonitor = setInterval(() => {
    // 取出当前选中的地址 ID


    // 如果有地址了，说明用户已选择或添加地址
    let address ; // 获取当前选中的地址id

    // let address = $(".address.active").data("id"); // 获取当前选中的地址id
    let selectedAddress;
    let currentOrderList;

    // console.log(address)

    // let $button1 = $('#submitCartItems');
    let $button2 = $('#submitItem');
    let $changeable = $('.changed');

    let priceText = $('.price span').text(); // 获取内部 <span> 的文本
    let priceValue = parseFloat(priceText); // 转换成浮点数

    let addressElement = document.querySelector('.address.active'); // 获取选中的地址

    // 获取各个字段的值
    // let province = addressElement.querySelector('.province').innerText;
    // let city = addressElement.querySelector('.city').innerText;
    // let district = addressElement.querySelector('.district').innerText;
    // let detail = addressElement.querySelector('.detail').innerText;
    // let receiver = addressElement.querySelector('.receiver').innerText;
    // let phone = addressElement.querySelector('.phone').innerText;

    let province ;
    let city ;
    let district ;
    let detail ;
    let receiver ;
    let phone ;

    // console.log(province, city, district, detail, receiver, phone);



    // }, 500); // 每500毫秒检查一次

    //获取地址
    function getAddress() {

        address = $(".address.active").data("id"); // 获取当前选中的地址id
        addressElement = document.querySelector('.address.active'); // 获取选中的地址


        province = addressElement.querySelector('.province').innerText;
        city = addressElement.querySelector('.city').innerText;
        district = addressElement.querySelector('.district').innerText;
        detail = addressElement.querySelector('.detail').innerText;
        receiver = addressElement.querySelector('.receiver').innerText;
        phone = addressElement.querySelector('.phone').innerText;

        // 组合地址字符串
        selectedAddress = `${province}省 ${city}市 ${district}区<br>
                       详细地址：${detail}<br>
                       收件人：${receiver}<br>
                       电话：${phone}`;
    }

    $('.address-grid').click(function () {
        getAddress();
        console.log(selectedAddress);
    });

    // $button1.click(function () {
    //     console.log("here1.....");

    //     // 新增订单
    //     $.ajax({
    //         url: "/CartHandler",
    //         type: "POST",
    //         data: { address: address }, // 直接传递字符串
    //         success: function (response) {
    //             if (response === "success") {
    //                 getAddress();
    //                 // 生成模态框的 HTML 结构
    //                 let modalHtml = `
    //                 <div id="orderModal" class="modal">
    //                     <div class="modal-content">
    //                         <h2 class="center">订单确认</h2> <!-- 修改为居中对齐 -->
    //                         <div class="countdown">
    //                             <span id="countdown-timer" style="color: red;">15:00</span> <!-- 设置红色字体 -->
    //                         </div> 
    //                         <div class="address-info">
    //                             <h2>收货地址</h2>
    //                             <p>${selectedAddress}</p>
    //                         </div>
    //                         <h2>商品详情</h2>
    //                         <div class="order-summary">
    //                             ${$(".orderTable").prop('outerHTML')} <!-- 复制订单信息 -->
    //                         </div>
    //                         <div class="total-container">
    //                             <span class="total-text">订单总价：</span>
    //                             <span class="price">¥<span>${priceValue}</span></span>
    //                             <span class="changed"><button class="submit-order" id="payCartOrder">支付</button>
    //                                                   <button class="submit-order" id="notPay">暂不支付</button></span>
    //                         </div>
    //                     </div>
    //                 </div>
    //             `;

    //                 // 将模态框添加到 body 中
    //                 $("body").append(modalHtml);

    //                 // 显示模态框
    //                 $("#orderModal").fadeIn();

    //                 // 15分钟倒计时
    //                 let timeLeft = 15 * 60; // 15分钟转为秒
    //                 let countdownTimer = setInterval(function () {
    //                     let minutes = Math.floor(timeLeft / 60);
    //                     let seconds = timeLeft % 60;
    //                     $("#countdown-timer").text(
    //                         `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`
    //                     );

    //                     if (timeLeft <= 0) {
    //                         clearInterval(countdownTimer);
    //                         alert("临时订单已过期！");
    //                         $("#orderModal").fadeOut(function () {
    //                             $(this).remove();
    //                         });
    //                     }

    //                     timeLeft--;
    //                 }, 1000);
    //             } else {
    //                 alert("提交订单失败，请稍后重试！");
    //             }
    //         },
    //         error: function () {
    //             alert("提交订单请求失败，请稍后重试！");
    //         },
    //     });
    // });


    $button2.click(function () {
        getAddress();
        console.log("here.....")
        var flag = localStorage.getItem('fromCart');
        console.log('flag' + flag)
        //从购物车来
        if (flag === '1') {
            //新增订单
            $.ajax({
                url: _util.getServerURL('order/CartSubmit'),
                type: "POST",
                data: {
                    userId: userId,
                    address: address
                },
                success: function (response) {
                    console.log(response)
                    if (response.status === 0) {
                        console.log(response.data)

                        currentOrderList = getCurrentOrderList(response.data)
                        console.log(currentOrderList)
                        getAddress();
                        // 生成模态框的 HTML 结构
                        let modalHtml = `
                        <div id="orderModal" style="
                            display: none;
                            position: fixed;
                            z-index: 9;
                            left: 0;
                            top: 0;
                            width: 100%;
                            height: 100%;
                            overflow: auto;
                            background-color: rgba(0, 0, 0, 0.5);
                            font-family: Arial, sans-serif;
                        ">
                            <div style="
                                background-color: #fff;
                                margin: 5% auto;
                                padding: 20px;
                                border: 1px solid #888;
                                width: 60%;
                                border-radius: 10px;
                                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                            ">
                                <h2 style="text-align: center;">订单确认</h2>
                                
                                <div class="countdown" style="text-align: center; margin-bottom: 10px;">
                                    <span id="countdown-timer" style="color: red; font-size: 18px;">15:00</span>
                                </div> 

                                <div style="margin-bottom: 20px;">
                                    <h3 style="margin-bottom: 5px;">收货地址</h3>
                                    <p>${selectedAddress}</p>
                                </div>

                                <h3 style="margin-bottom: 10px;">商品详情</h3>
                                <div class="order-summary" style="margin-bottom: 20px;">
                                    ${$(".orderTable").prop('outerHTML')}
                                </div>

                                <div style="
                                    display: flex;
                                    justify-content: space-between;
                                    align-items: center;
                                    border-top: 1px solid #eee;
                                    padding-top: 15px;
                                ">
                                    <div style="font-weight: bold; font-size: 16px;">订单总价：</div>
                                    <div style="color: #e91e63; font-size: 20px;">¥<span>${priceValue}</span></div>
                                    <div>
                                        <button class="submit-order" id="payOrder" style="
                                            padding: 8px 16px;
                                            margin-left: 10px;
                                            background-color: #4CAF50;
                                            color: white;
                                            border: none;
                                            border-radius: 5px;
                                            cursor: pointer;
                                        ">支付</button>
                                        <button class="submit-order" id="notPay" style="
                                            padding: 8px 16px;
                                            margin-left: 10px;
                                            background-color: #ccc;
                                            color: black;
                                            border: none;
                                            border-radius: 5px;
                                            cursor: pointer;
                                        ">暂不支付</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;


                        // 将模态框添加到 body 中
                        $("body").append(modalHtml);

                        // 显示模态框
                        $("#orderModal").fadeIn();



                        // 15分钟倒计时
                        let timeLeft = 15 * 60; // 15分钟转为秒
                        let countdownTimer = setInterval(function () {
                            let minutes = Math.floor(timeLeft / 60);
                            let seconds = timeLeft % 60;
                            $("#countdown-timer").text(
                                `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`
                            );

                            if (timeLeft <= 0) {
                                clearInterval(countdownTimer);
                                alert("临时订单已过期！");
                                $("#orderModal").fadeOut(function () {
                                    $(this).remove();
                                });
                            }

                            timeLeft--;
                        }, 1000);
                    } else {
                        alert("该商品已售罄！")
                    }
                },
                error: function (xhr, status, error) {
                    console.error("状态码:", xhr.status);  // HTTP 状态码
                    console.error("响应文本:", xhr.responseText);  // 服务器返回的错误信息
                    console.error("错误:", error);  // jQuery 解析错误信息
                    alert("提交订单失败，请稍后重试！错误码：" + xhr.status);
                }
            });
        } else {
            var item = JSON.parse(localStorage.getItem('selectedItem'));
            console.log(item)
            console.log('address: ' + address)
            //新增订单
            $.ajax({
                url: _util.getServerURL('order/ItemSubmit'),
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify({
                    userId: userId,
                    addressID: address,
                    item: item
                }),
                success: function (response) {
                    console.log(response)
                    if (response.status === 0) {
                        currentOrderList = getCurrentOrderList(response.data)
                        console.log(currentOrderList)
                        getAddress();
                        // 生成模态框的 HTML 结构
                        let modalHtml = `
                        <div id="orderModal" style="
                            display: none;
                            position: fixed;
                            z-index: 9;
                            left: 0;
                            top: 0;
                            width: 100%;
                            height: 100%;
                            overflow: auto;
                            background-color: rgba(0, 0, 0, 0.5);
                            font-family: Arial, sans-serif;
                        ">
                            <div style="
                                background-color: #fff;
                                margin: 5% auto;
                                padding: 20px;
                                border: 1px solid #888;
                                width: 60%;
                                border-radius: 10px;
                                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                            ">
                                <h2 style="text-align: center;">订单确认</h2>
                                
                                <div class="countdown" style="text-align: center; margin-bottom: 10px;">
                                    <span id="countdown-timer" style="color: red; font-size: 18px;">15:00</span>
                                </div> 

                                <div style="margin-bottom: 20px;">
                                    <h3 style="margin-bottom: 5px;">收货地址</h3>
                                    <p>${selectedAddress}</p>
                                </div>

                                <h3 style="margin-bottom: 10px;">商品详情</h3>
                                <div class="order-summary" style="margin-bottom: 20px;">
                                    ${$(".orderTable").prop('outerHTML')}
                                </div>

                                <div style="
                                    display: flex;
                                    justify-content: space-between;
                                    align-items: center;
                                    border-top: 1px solid #eee;
                                    padding-top: 15px;
                                ">
                                    <div style="font-weight: bold; font-size: 16px;">订单总价：</div>
                                    <div style="color: #e91e63; font-size: 20px;">¥<span>${priceValue}</span></div>
                                    <div>
                                        <button class="submit-order" id="payOrder" style="
                                            padding: 8px 16px;
                                            margin-left: 10px;
                                            background-color: #4CAF50;
                                            color: white;
                                            border: none;
                                            border-radius: 5px;
                                            cursor: pointer;
                                        ">支付</button>
                                        <button class="submit-order" id="notPay" style="
                                            padding: 8px 16px;
                                            margin-left: 10px;
                                            background-color: #ccc;
                                            color: black;
                                            border: none;
                                            border-radius: 5px;
                                            cursor: pointer;
                                        ">暂不支付</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;


                        // 将模态框添加到 body 中
                        $("body").append(modalHtml);

                        // 显示模态框
                        $("#orderModal").fadeIn();



                        // 15分钟倒计时
                        let timeLeft = 15 * 60; // 15分钟转为秒
                        let countdownTimer = setInterval(function () {
                            let minutes = Math.floor(timeLeft / 60);
                            let seconds = timeLeft % 60;
                            $("#countdown-timer").text(
                                `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`
                            );

                            if (timeLeft <= 0) {
                                clearInterval(countdownTimer);
                                alert("临时订单已过期！");
                                $("#orderModal").fadeOut(function () {
                                    $(this).remove();
                                });
                            }

                            timeLeft--;
                        }, 1000);
                    } else {
                        alert("该商品已售罄！")
                    }
                },
                error: function (xhr, status, error) {
                    console.error("状态码:", xhr.status);  // HTTP 状态码
                    console.error("响应文本:", xhr.responseText);  // 服务器返回的错误信息
                    console.error("错误:", error);  // jQuery 解析错误信息
                    alert("提交订单失败，请稍后重试！错误码：" + xhr.status);
                }
            });
        }

    });

    // // 状态转换（给动态创建的按钮绑定事件）
    // $(document).on('click', '#payCartOrder', function () {
    //     console.log('here2....');
    //     $.ajax({
    //         url: "/statusChangeTo1",
    //         type: "POST",
    //         data: { nextStatus: "1", behavior: "payCartOrder" }, // 直接传递字符串
    //         success: function (response) {
    //             if (response === "success") {
    //                 alert("支付成功！即将跳回主页");
    //                 window.location.href = "/mainForm"; // 回到主页
    //             } else {
    //                 alert("1:支付失败，请稍后重试！");
    //             }
    //         },
    //         error: function (xhr, status, error) {
    //             console.error("状态码:", xhr.status);  // HTTP 状态码
    //             console.error("响应文本:", xhr.responseText);  // 服务器返回的错误信息
    //             console.error("错误:", error);  // jQuery 解析错误信息
    //             alert("2:支付失败，请稍后重试！错误码：" + xhr.status);
    //         }
    //     });
    // });

    // 状态转换（给动态创建的按钮绑定事件）
    $(document).on('click', '#payOrder', function () {
        getAddress();
        console.log('here2....');
        var flag = localStorage.getItem('fromCart');
        var behavior;

        if (flag) {
            behavior = 'payCartOrder'
        } else {
            behavior = 'payOrder'
        }

        $.ajax({
            url: _util.getServerURL('order/orderStatus'),
            type: "PUT",
            contentType: 'application/json',
            data: JSON.stringify(
                { userId: userId, behavior: behavior, nextStatus: 1, currentOrderList: currentOrderList }
            ), // 发送的请求数据，包含按钮ID
            success: function (response) {
                if (response.status === 0) {
                    console.log(response);
                    alert("支付成功！即将跳回主页");
                    window.location.href = "./user_main.html"; // 回到主页
                } else {
                    alert("1:支付失败，请稍后重试！");
                }
            },
            error: function (xhr, status, error) {
                console.error("状态码:", xhr.status);  // HTTP 状态码
                console.error("响应文本:", xhr.responseText);  // 服务器返回的错误信息
                console.error("错误:", error);  // jQuery 解析错误信息
                alert("2:支付失败，请稍后重试！错误码：" + xhr.status);
            }
        });
    });

    //不想支付
    $(document).on('click', '#notPay', function () {
        getAddress();
        window.location.href = "./user_main.html"; // 回到主页
    });


});